<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{padding: 0;margin: 0;}
        .box{
            width: 200px;
            height: 200px;
            background-color: #6ff;
            margin: 50px;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
<script>
    var box = document.getElementsByClassName("box")[0];

    // 问题: 函数嵌套调用过程中,会出现多个this指向,this指向冲突  
    // 解决方法1:
    // 1. 提前声明中间变量(_this  that) 存储this指向
    // 2. 借助bind  bind()方法返回新函数 新函数调用时this指向外层的this(obj)
    // 3. 借助箭头函数 向外跳一层找父作用域 


    // 封装一个函数  传入一个元素,给该元素绑定点击事件, 点击时随机颜色;
    var obj = {
        ele:box,
        bindEvent:function(){
            // this -> obj
            console.log("bindEvenet:",this);
            // 方法2: bind()方法返回新函数 新函数调用时this指向外层的this(obj)
            this.ele.addEventListener("click",() => {
                console.log("click",this);  // this -> obj
                this.ele.style.backgroundColor = this.randColor();
            });
        },
        randColor:function(){
            var colorStr = "0123456789abcdef";
            var str = "#";
            for(var i=0;i<6;i++){
                var index = Math.floor(Math.random()*colorStr.length); // 0-15
                var char = colorStr.charAt(index);
                // console.log(num,char);
                str += char;
            }
            console.log(str);
            return str;
        }
    }

    obj.bindEvent();



    



</script>
<script>
    /* 
        function eleClickRandColor(ele){
        var obj = {
            ele:box,
            bindEvent:function(){
                // this -> obj
                console.log("bindEvenet:",this);
                var  _this = this;  // _this也引用obj

                this.ele.addEventListener("click",function(){
                    // this -> 绑定事件的元素 (box)
                    console.log("click",this,_this);
                    this.style.backgroundColor = _this.randColor();
                })
            
            },
            randColor:function(){
                var colorStr = "0123456789abcdef";
                var str = "#";
                for(var i=0;i<6;i++){
                    var index = Math.floor(Math.random()*colorStr.length); // 0-15
                    var char = colorStr.charAt(index);
                    // console.log(num,char);
                    str += char;
                }
                console.log(str);
                return str;
            }
        }
        obj.bindEvent();
        return obj;
    }
    
    
    
    */


</script>
</html>